package ltd.sshine.networkserver.port;

import ltd.sshine.networkserver.exception.PortCheckException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class RangePortHandler implements PortHandler{
    private final Pattern compile = Pattern.compile("^(\\d+)-(\\d+)$");
    @Override
    public boolean check(String port) throws PortCheckException {
        Matcher matcher = compile.matcher(port);
        boolean b = matcher.find();
        if (b){
            int left= Integer.parseInt(matcher.group(1));
            int right= Integer.parseInt(matcher.group(2));
            if (left>right){
                throw new PortCheckException(left+"大于"+right);
            }
        }
        return b;
    }

    @Override
    public int genPort(String port, List<Integer> ignore) {
        Matcher matcher = compile.matcher(port);
        boolean b = matcher.find();
        if (b){
            int left= Integer.parseInt(matcher.group(1));
            int right= Integer.parseInt(matcher.group(2));
            for (int i = left; i <= right; i++) {
                if (ignore.contains(i)) {
                    continue;
                }
                return i;
            }
        }
        return -1;
    }
}
